package com.acane.instagram.feature.postDetail

import android.annotation.SuppressLint
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import coil.compose.AsyncImage
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.design.theme.InstagramBlue
import com.acane.instagram.core.design.theme.InstagramDarkGray
import com.acane.instagram.core.design.theme.InstagramLightGray
import com.acane.instagram.core.extension.clickableNoRipple
import com.acane.instagram.core.model.PostInfo
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.core.model.dto.CommentDTO
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import com.acane.instagram.feature.common.SessionManager
import com.acane.instagram.feature.home.CommentList
import com.acane.instagram.feature.home.HomeViewModel
import com.acane.instagram.feature.home.ImageCarousel
import com.acane.instagram.feature.notification.NotificationViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun PostDetailRoute(
    toProfile: (String) -> Unit,
    navController: NavController,
    initialCommentId: String? = null, // 接收可选参数
    homeViewModel: HomeViewModel = viewModel(),
    viewModel: PostDetailViewModel = viewModel()
    //savedStateHandle: SavedStateHandle, // 添加 SavedStateHandle

) {
    // 从导航参数中获取 postId 和 commentId
    //val postId = savedStateHandle.get<String>(POST_DETAIL_ROUTE_WITH_POST_ID) ?: ""
    //val initialCommentId = savedStateHandle.get<String?>(COMMENT_ID_PARAM)


    // 将参数传递给 ViewModel
//    val viewModel: PostDetailViewModel = viewModel(
//        factory = PostDetailViewModel.provideFactory(postId)
//    )

    val isFollowingMap by homeViewModel.isFollowingMap.collectAsState() // 收集 isFollowingMap 的状态
//    val viewModel: PostDetailViewModel = viewModel()
    val notificationViewModel: NotificationViewModel = viewModel()

    val commentBottomSheetState =
        remember { ModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden) }


    // 初始化目标评论
    LaunchedEffect(initialCommentId) {
        initialCommentId?.let {
            viewModel.setTargetComment(it)
            viewModel.loadComments() // 确保重新加载评论
        }
    }
//    // 初始化目标评论（如果有）
//    LaunchedEffect(initialCommentId) {
//        initialCommentId?.let {
//            viewModel.setTargetComment(it)
//        }
//    }
    PostDetailScreen(
        toProfile = toProfile,
        navController = navController,
        postDetailViewModel = viewModel,
        notificationViewModel = notificationViewModel,
        isFollowingMap = isFollowingMap,
        commentBottomSheetState = commentBottomSheetState,
    )
}

@SuppressLint("SuspiciousIndentation")
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
@Composable
fun PostDetailScreen(
    toProfile: (String) -> Unit,
    navController: NavController,
    postDetailViewModel: PostDetailViewModel,
    notificationViewModel: NotificationViewModel,
    isFollowingMap: Map<String, Boolean>,
    commentBottomSheetState: ModalBottomSheetState,
) {


//    val commentNotification = notificationViewModel.commentNotification.collectAsState()
//    val commentDatum = commentNotification.value

    // 替换原来的commentDatum为ViewModel的comments
    val comments by postDetailViewModel.comments.collectAsState()


//    Log.d("PostDetailScreen", "帖子详情的评论数据: $commentDatum")
    Scaffold(
        topBar = {
            TopAppBar(
                navigationIcon = {
                    IconButton(onClick = {
                        navController.popBackStack()
                    }) {
                        Image(
                            painter = painterResource(id = R.drawable.arrow_left),
                            contentDescription = "返回",
                            modifier = Modifier.size(24.dp),
                            contentScale = ContentScale.Fit
                        )
                    }
                },
                title = {
                    Text("帖子", fontWeight = FontWeight.Bold)
                },
                actions = {

                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.White
                ),
            )
        },
        containerColor = Color.White,
    ) { padding ->
        val coroutineScope = rememberCoroutineScope()
        val postData by postDetailViewModel.postData.collectAsState()
        Log.d("PostDetailScreen", "PostDetailScreen: $postData")
        //
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            postData?.let {
                PostDetailItem(
                    notificationViewModel = notificationViewModel,
                    postDetailViewModel = postDetailViewModel,
                    postInfo = it,
                    toProfile = toProfile,
                    isAutoPlay = true, // 传递播放状态
                    coroutineScope = coroutineScope,
                    commentDatum = comments,
                    isFollowingMap = isFollowingMap,
                    commentBottomSheetState = commentBottomSheetState,
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterialApi::class)
@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun PostDetailItem(
    commentDatum: List<CommentDTO>,
    notificationViewModel: NotificationViewModel,
    postDetailViewModel: PostDetailViewModel,
    postInfo: PostInfo,
    toProfile: (String) -> Unit,
    isAutoPlay: Boolean,
    coroutineScope: CoroutineScope,
    isFollowingMap: Map<String, Boolean>,
    homeViewModel: HomeViewModel = viewModel(),
    commentBottomSheetState: ModalBottomSheetState,
) {
    val context = LocalContext.current
    // 添加状态变量来跟踪回复的评论
    var replyToComment by remember { mutableStateOf<CommentDTO?>(null) }

    val isFollowing = isFollowingMap[postInfo.user.id] ?: false // 使用 isFollowingMap 获取状态
    val (isPostLiked, setIsPostLiked) = remember { mutableStateOf(false) }
    val (isCollected, setIsCollected) = remember { mutableStateOf(false) }

    var postLikes by remember { mutableStateOf(postInfo.likeCount) }

    LaunchedEffect(Unit) { // 使用 Unit 确保只执行一次
        coroutineScope.launch(Dispatchers.IO) {
            val isLikedResponse = MyRetrofitDatasource.judgeIsLiked(
                postInfo.id,
                SessionManager.currentUser?.id
            ).data == true
            setIsPostLiked(isLikedResponse)
            Log.d("PostDetail", "🟢 初始化点赞状态：$isLikedResponse")
        }
    }
    // 初始化收藏状态
    LaunchedEffect(Unit) { // 使用 Unit 确保只执行一次
        coroutineScope.launch(Dispatchers.IO) {
            val isCollectedResponse = MyRetrofitDatasource.judgeIsCollected(
                postInfo.id,
                SessionManager.currentUser?.id
            ).data == true

            setIsCollected(isCollectedResponse)
            Log.d("HomeRoute", "🟢 初始化收藏状态：$isCollectedResponse")
        }
    }
    // 加载关注状态
    LaunchedEffect(Unit) {
        coroutineScope.launch(Dispatchers.IO) {
            val isFollowingResponse = MyRetrofitDatasource.judgeIsFollowed(
                postInfo.user.id!!,
                SessionManager.currentUser?.id
            ).data == true
            homeViewModel.setIsFollowing(postInfo.user.id, isFollowingResponse)
        }
    }

    var isExpanded by remember { mutableStateOf(false) } // 添加展开状态

    val commentData = commentDatum.filter { it.postId == postInfo.id }
    Log.d("PostDetail", "帖子id：${postInfo.id}\n过滤后的评论数据：$commentData")
    // 添加滚动控制
    val listState = rememberLazyListState()

    var selectedPostUser by remember { mutableStateOf<UserInfo?>(null) }

    LaunchedEffect(postInfo) {
        // 默认设置 selectedPostUser 为 postInfo.user
        selectedPostUser = postInfo.user
    }

    val focusRequester = remember { FocusRequester() }

//    // 改为监听 comments 变化
//    LaunchedEffect(commentDatum) {
//        postDetailViewModel.targetCommentId?.let { targetId ->
//            val index = commentDatum.indexOfFirst { it.id == targetId }
//            if (index != -1) {
//                delay(300) // 等待列表渲染完成
//                listState.animateScrollToItem(index)
//                postDetailViewModel.clearTargetComment()
//            }
//        }
//    }
//    // 当评论加载完成且存在目标评论时
    LaunchedEffect(commentData.isNotEmpty(), postDetailViewModel.targetCommentId) {
        postDetailViewModel.targetCommentId?.let { targetId ->
            val index = commentData.indexOfFirst { it.id == targetId }
            if (index != -1) {
                listState.animateScrollToItem(
                    index = index,
                )
                // 延迟清除状态避免重复触发
                delay(1500)
                postDetailViewModel.clearTargetComment()
            }
        }
    }

    Column(
        modifier = Modifier.fillMaxWidth(),
    ) {

        LazyColumn(
            state = listState,
            modifier = Modifier.weight(1f)
        ) {
            item {
                Column(
                    modifier = Modifier.padding(vertical = 8.dp),
                    horizontalAlignment = Alignment.Start
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Spacer(modifier = Modifier.size(8.dp))
                            //发布者头像
                            AsyncImage(model = postInfo.user.avatar?.let {
                                val url = "${Config.ADDRESS}avatars/$it"
                                Log.d("HomeRoute", "🟢 尝试加载头像 URL: $url")
                                url
                            } ?: run {
                                Log.d("HomeRoute", "🔴 无服务器头像文件名，显示默认头像")
                                R.drawable.ic_default_avatar
                            },
                                contentDescription = "发布者头像",
                                modifier = Modifier
                                    .size(30.dp)
                                    .clip(CircleShape)
                                    .background(Color.Transparent)
                                    .clickableNoRipple {
                                        postInfo.user.id?.let { toProfile(it) }
                                    },
                                contentScale = ContentScale.Crop,
                                error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                            )
                            Spacer(modifier = Modifier.width(8.dp)) // 添加左右间距
                            //昵称
                            postInfo.user.nickName?.let {
                                androidx.compose.material.Text(
                                    text = it,
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.Bold,
                                    color = Color.Black
                                )
                            }
                            Spacer(modifier = Modifier.weight(1.0f)) // 添加左右间距
                            // 关注按钮
                            if (!isFollowing && postInfo.user.id != SessionManager.currentUser?.id) {
                                Button(
                                    onClick = {
                                        // 发送关注请求
                                        coroutineScope.launch(Dispatchers.IO) {
                                            homeViewModel.sendFollowRequest(
                                                postInfo.user.id!!,
                                                SessionManager.currentUser?.id!!
                                            )
                                        }
                                        homeViewModel.setIsFollowing(postInfo.user.id!!, true)
                                    },
                                    colors = ButtonDefaults.buttonColors(
                                        containerColor = InstagramLightGray,
                                        contentColor = InstagramDarkGray
                                    ),
                                    modifier = Modifier
                                        .height(30.dp)
                                        .padding(horizontal = 4.dp), // 减少水平内边距
                                    shape = RoundedCornerShape(5.dp),
                                    elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                                    contentPadding = PaddingValues(
                                        horizontal = 8.dp,
                                        vertical = 0.dp
                                    ) // 设置内容内边距
                                ) {
                                    Text(
                                        text = "关注",
                                        fontSize = 12.sp,
                                        fontWeight = FontWeight.Bold
                                    )
                                }
                            }
                            Image(
                                painter = painterResource(id = R.drawable.options_vertical),
                                contentDescription = "options",
                                modifier = Modifier.size(24.dp)
                            )
                        }

                    }
                    Spacer(modifier = Modifier.height(8.dp)) // 添加左右间距
                    ImageCarousel(
                        postInfo = postInfo,
                        isLiked = isPostLiked,
                        onLikeClick = {
                            val newIsLiked = !isPostLiked // 先计算新状态
                            setIsPostLiked(newIsLiked)    // 立即更新本地状态

                            if (newIsLiked) {         // 根据新状态执行操作
                                postLikes += 1
                                coroutineScope.launch {
                                    MyRetrofitDatasource.likePost(postInfo.id)
                                    notificationViewModel.sendLikeNotification(
                                        SessionManager.currentUser?.id!!,
                                        postInfo.id
                                    )
                                }
                            } else {
                                postLikes -= 1
                                coroutineScope.launch {
                                    MyRetrofitDatasource.unlikePost(postInfo.id)
                                }
                            }
                        },
                        isAutoPlay = isAutoPlay,
                        isCollected = isCollected,
                        onCommentClick = {
                            selectedPostUser = postInfo.user
                        },
                        onCollectClick = {
                            val newIsCollected = !isCollected // 先计算新状态
                            setIsCollected(newIsCollected)
                            if (newIsCollected) {
                                coroutineScope.launch {
                                    MyRetrofitDatasource.collectPost(postInfo.id, SessionManager.currentUser?.id!!)
                                    // 提示收藏成功
                                    Toast.makeText(context, "收藏成功", Toast.LENGTH_SHORT).show()
                                }
                            } else {
                                coroutineScope.launch {
                                    MyRetrofitDatasource.unCollectPost(postInfo.id, SessionManager.currentUser?.id!!)
                                    // 提示取消收藏
                                    Toast.makeText(context, "取消收藏", Toast.LENGTH_SHORT).show()
                                }
                            }
                        }
                    )
                    Spacer(modifier = Modifier.height(6.dp)) // 添加底部内边距
                    //点赞量
                    Text(
                        text = "${postLikes}次赞",
                        fontSize = 12.sp,
                        modifier = Modifier.padding(start = 8.dp)
                    )
                    Spacer(modifier = Modifier.height(6.dp)) // 添加底部内边距
                    //文案
                    ClickableText(text = buildAnnotatedString {
                        val text =
                            if (isExpanded) postInfo.content else "${postInfo.content?.take(50)}...展开"
                        append(text)
                        if (!isExpanded) {
                            text?.let {
                                addStyle(
                                    style = SpanStyle(color = InstagramDarkGray),
                                    start = text.length - 3,
                                    end = it.length
                                )
                            }
                        }
                    },
                        style = TextStyle(fontSize = 12.sp),
                        modifier = Modifier
                            .padding(start = 8.dp)
                            .clickable { isExpanded = !isExpanded }, // 添加 onClick 回调
                        overflow = TextOverflow.Ellipsis,
                        maxLines = if (isExpanded) Int.MAX_VALUE else 2, // 设置 maxLines
                        onClick = { isExpanded = !isExpanded } // 添加 onClick 回调
                    )
                    Spacer(modifier = Modifier.height(6.dp)) // 添加底部内边距
                    //发布日期
                    postInfo.createdTime?.let {
                        androidx.compose.material.Text(
                            text = it,
                            fontSize = 10.sp,
                            color = InstagramDarkGray,
                            modifier = Modifier.padding(start = 8.dp)
                        )
                    }
                    Spacer(modifier = Modifier.size(8.dp))
                    // 分割线
                    Divider(modifier = Modifier.fillMaxWidth(), color = InstagramLightGray)
                    Spacer(modifier = Modifier.size(8.dp))
                }
            }
            // 评论区域
            item {
                val groupedComments = commentData.groupBy {
                    when {
                        it.parentId.isNullOrEmpty() -> "root"
                        else -> it.parentId
                    }
                }
                Log.d("groupedComments", groupedComments["root"].toString())
                if (selectedPostUser != null){
                    selectedPostUser?.let {
                        CommentList(
                            comments = groupedComments["root"] ?: emptyList(),
                            groupedComments = groupedComments,
                            onReplyClick = { replyToComment = it },
                            notificationViewModel = notificationViewModel,
                            homeViewModel = homeViewModel,
                            scope = coroutineScope,
                            selectedPostUser = it,
                            toProfile = toProfile,
                            commentBottomSheetState = commentBottomSheetState,
                            focusRequester = focusRequester,
                        )
                    }
                }
            }
        }

        CommentBar(
            replyToComment = replyToComment,
            postDetailViewModel = postDetailViewModel,
            onSendComment = {
                val newComment = CommentDTO(
                    id = "",
                    commenterId = SessionManager.currentUser?.id!!,
                    postId = postInfo.id,
                    content = postDetailViewModel.caption,
                    timestamp = "",
                    likes = 0,
                    parentId = replyToComment?.id ?: "",
                )
                postDetailViewModel.sendComment(newComment)
                notificationViewModel.sendMessageNotification(
                    commenterId = SessionManager.currentUser?.id!!,
                    postId = postInfo.id,
                    content = postDetailViewModel.caption,
                )
                Log.d("PostDetailRoute", "🟢 发送评论：${postDetailViewModel.caption}")
                postDetailViewModel.caption = ""
                replyToComment = null
            },
            focusRequester = focusRequester,
        )
    }
}

@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun CommentBar(
    postDetailViewModel: PostDetailViewModel,
    onSendComment: () -> Unit,
    replyToComment: CommentDTO?,
    focusRequester: FocusRequester,
) {
    Divider(modifier = Modifier.fillMaxWidth(), color = InstagramLightGray)
    Row(
        modifier = Modifier
            .fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically
    ) {
        val scope = rememberCoroutineScope()
        // 内部状态
        var replyToCommenter by remember { mutableStateOf<UserInfo?>(null) }
        var commenterName by remember { mutableStateOf("") }
        var displayText by remember { mutableStateOf("") }

        val commenter = SessionManager.currentUser


        // 发送评论逻辑
        val sendComment: () -> Unit = {
            if (displayText.isNotBlank()) {
                postDetailViewModel.caption = displayText.removePrefix("@${commenterName}：")
                onSendComment() // 调用外部传入的 onSendComment
                postDetailViewModel.caption = ""
                replyToCommenter = null
                commenterName = ""
                displayText = ""
            }
        }


        LaunchedEffect(replyToComment) {
            val commenterId = replyToComment?.commenterId
            if (commenterId != null) {
                replyToCommenter = MyRetrofitDatasource.getUserById(commenterId).data
                commenterName = replyToCommenter?.userName ?: ""
                displayText = "@${commenterName}："
                postDetailViewModel.caption = ""
            } else {
                replyToCommenter = null
                commenterName = ""
                displayText = postDetailViewModel.caption
            }
        }
        //发布者头像
        AsyncImage(model = commenter?.avatar?.let {
            val url = "${Config.ADDRESS}avatars/$it"
            Log.d("HomeRoute", "🟢 尝试加载头像 URL: $url")
            url
        } ?: run {
            Log.d("HomeRoute", "🔴 无服务器头像文件名，显示默认头像")
            R.drawable.ic_default_avatar
        },
            contentDescription = "发布者头像",
            modifier = Modifier
                .size(30.dp)
                .clip(CircleShape)
                .background(Color.Transparent),
            contentScale = ContentScale.Crop,
            error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
        )

        TextField(
            value = displayText,
            onValueChange = { newValue ->
                // 处理输入：当有回复时，禁止删除 "@userName：" 前缀
                if (replyToComment != null) {
                    val prefix = "@${commenterName}："
                    if (newValue.startsWith(prefix)) {
                        displayText = newValue
                        postDetailViewModel.caption = newValue.removePrefix(prefix)
                    }
                } else {
                    displayText = newValue
                    postDetailViewModel.caption = newValue
                }
            },
            placeholder = {
                Text(
                    text = "添加评论...",
                    color = Color.Gray
                )
            },
            modifier = Modifier
                .weight(1f)
                .focusRequester(focusRequester),
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = Color.Transparent, // 设置背景颜色为透明
                focusedIndicatorColor = Color.Transparent, // 设置聚焦时的指示线颜色为透明
                unfocusedIndicatorColor = Color.Transparent, // 设置未聚焦时的指示线颜色为透明
            ),
            textStyle = MaterialTheme.typography.body1.copy(color = MaterialTheme.colors.onSurface) // 设置文本颜色
        )
        if (postDetailViewModel.caption.isBlank()) {
            Image(
                painter = painterResource(id = R.drawable.emoji),
                contentDescription = null,
                modifier = Modifier
                    .size(35.dp)
                    .padding(end = 10.dp)
            )
        } else {
            Box(
                modifier = Modifier
                    .padding(end = 10.dp)
                    .size(30.dp)
                    .clip(RoundedCornerShape(15.dp))
                    .background(InstagramBlue)
                    .clickableNoRipple {
                        sendComment()
                    },
            ) {
                Image(
                    painter = painterResource(id = R.drawable.send),
                    contentDescription = null,
                    modifier = Modifier
                        .size(30.dp)
                )
            }
        }
    }
}
